/*
 * Copyright 2008 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.jas.linker;

import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.Artifact;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.CompilationResult;
import com.google.gwt.core.ext.linker.ConfigurationProperty;
import com.google.gwt.core.ext.linker.EmittedArtifact;
import com.google.gwt.core.ext.linker.LinkerOrder;
import com.google.gwt.core.ext.linker.SelectionProperty;
import com.google.gwt.core.ext.linker.Shardable;
import com.google.gwt.core.ext.linker.LinkerOrder.Order;
import com.google.gwt.core.ext.linker.impl.SelectionScriptLinker;
import com.google.gwt.dev.About;
import com.google.gwt.dev.util.DefaultTextOutput;

import java.util.Collection;
import java.util.Set;
import java.util.SortedSet;

/**
 * A Linker for producing a single JavaScript file from a GWT module. The use of
 * this Linker requires that the module has exactly one distinct compilation
 * result.
 */
@LinkerOrder(Order.PRIMARY)
@Shardable
public class FlashLinker extends SelectionScriptLinker {
  @Override
  public String getDescription() {
    return "Flash";
  }

  @Override
  public ArtifactSet link(TreeLogger logger, LinkerContext context,
      ArtifactSet artifacts, boolean onePermutation)
      throws UnableToCompleteException {
    if (onePermutation) {
      permutationsUtil.setupPermutationsMap(artifacts);
      ArtifactSet toReturn = new ArtifactSet(artifacts);
      toReturn.add(emitSelectionScript(logger, context, artifacts));
      return toReturn;
    } else {
      return artifacts;
    }
  }

  @Override
  protected Collection<Artifact<?>> doEmitCompilation(TreeLogger logger,
      LinkerContext context, CompilationResult result, ArtifactSet artifacts)
      throws UnableToCompleteException {
    if (result.getJavaScript().length != 1) {
      logger.branch(TreeLogger.ERROR,
          "The module must not have multiple fragments when using the "
              + getDescription() + " Linker.", null);
      throw new UnableToCompleteException();
    }
    return super.doEmitCompilation(logger, context, result, artifacts);
  }

  @Override
  protected EmittedArtifact emitSelectionScript(TreeLogger logger,
      LinkerContext context, ArtifactSet artifacts)
      throws UnableToCompleteException {

    DefaultTextOutput out = new DefaultTextOutput(true);
    out.print("package {\n");
    // super-hack, just import EVERYTHING until auto-import generation added
    SortedSet<FlashImportsArtifact> imports = artifacts
        .find(FlashImportsArtifact.class);

    if (imports != null && imports.size() > 0) {
      FlashImportsArtifact one = imports.first();
      Set<String> importStmts = one.getImports();
      // needed by main class
      importStmts.add("flash.display.Sprite");
      // needed by timer dependencies
      importStmts.add("flash.utils.*");
      importStmts.add("flash.external.ExternalInterface");


      for (String importStmt : importStmts) {
        out.print("import " + importStmt + ";\n");
      }
    }
    out.print("public class " + context.getModuleName() + " extends Sprite {\n"
        + " public function " + context.getModuleName() +"() {\n"
        + "  var $moduleName, $moduleBase;\n"
        // redirect select $wnd functions to global flash functions
        + "  var $wnd = { setTimeout: flash.utils.setTimeout, setInterval: flash.utils.setInterval, clearTimeout: flash.utils.clearTimeout, clearInterval: flash.utils.clearInterval };\n"
        + "  var window = $wnd;\n"
        + "  var $doc = this;\n"
        + "  var $sessionId = null;"
        + "  var $root = this; "
        + "  var $Null = null; \n");
    
    out.print("var $stats = null;");
    out.newlineOpt();
    // register error handler
    boolean isStackEmul = true;
    for (SelectionProperty p : context.getProperties()) {
      if (p.getName().equals("compiler.stackMode") && "emulated".equals(p.tryGetValue())) {
        isStackEmul = true;
        break;
      }
    }

    boolean recordLocation = true;
    for (ConfigurationProperty cp : context.getConfigurationProperties()) {
      if (cp.getName().equals("compiler.emulatedStack.recordFileNames") && "true".equals(cp.getValue())) {
        recordLocation = true;
        break;
      }
    }

    out.print("$root.loaderInfo.uncaughtErrorEvents.addEventListener(\"uncaughtError\", function(event) {\n"
        + "        var i = 0;\n"
        + "        var stackMsg = \"\";\n"
//        + "        for (i = 0; i <= $stackDepth_0; i++) {\n"
//        + "           stackMsg += \" in \" + $stack_0[i] + \"(\" + $location_0[i]+\")\\n\"\n"
//        + "           }\n"
        + "\n"
        + "        flash.external.ExternalInterface.call(\"alert\", event.toString() + \"\\n\" + stackMsg);"
        + "});\n");
    // Find the single CompilationResult
    Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    if (results.size() != 1) {
      logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
          + " permutation when using the " + getDescription() + " Linker.",
          null);
      throw new UnableToCompleteException();
    }
    CompilationResult result = results.iterator().next();

    out.print("var $strongName = '" + result.getStrongName() + "';");
    out.newlineOpt();

    String[] js = result.getJavaScript();
    if (js.length != 1) {
      logger.log(TreeLogger.ERROR,
          "The module must not have multiple fragments when using the "
              + getDescription() + " Linker.", null);
      throw new UnableToCompleteException();
    }
    out.print(js[0]);

    // Generate the call to tell the bootstrap code that we're ready to go.
    out.newlineOpt();        
    out.print("trace('About to invoke entry point');\n  gwtOnLoad(null, \""+context.getModuleName()+"\", null);\n" + 
        "                        }\n" + 
        "                    } }");

    return emitString(logger, out.toString(), context.getModuleName()
        + ".as");
  }

  /**
   * Unimplemented. Normally required by
   * {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult)}.
   */
  @Override
  protected String getCompilationExtension(TreeLogger logger,
      LinkerContext context) throws UnableToCompleteException {
    throw new UnableToCompleteException();
  }

  /**
   * Unimplemented. Normally required by
   * {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult)}.
   */
  @Override
  protected String getModulePrefix(TreeLogger logger, LinkerContext context,
      String strongName) throws UnableToCompleteException {
    throw new UnableToCompleteException();
  }

  /**
   * Unimplemented. Normally required by
   * {@link #doEmitCompilation(TreeLogger, LinkerContext, CompilationResult)}.
   */
  @Override
  protected String getModuleSuffix(TreeLogger logger, LinkerContext context)
      throws UnableToCompleteException {
    throw new UnableToCompleteException();
  }

  @Override
  protected String getSelectionScriptTemplate(TreeLogger logger, LinkerContext context)
      throws UnableToCompleteException {
    return "com/google/gwt/core/linker/SingleScriptTemplate.js";
  }
}
